<template>
  <div 
    ref="controlPanelRef" 
    class="floating-control-panel" 
    :class="{ 'draggable': !isFixed, 'fixed': isFixed }"
  >
    <div class="control-panel">
      <!-- 方向键（左侧） -->
      <div class="direction-controls">
        <tui-button v-if="visibleButtons.includes('up')" circle @click="handleDirectionChange('up')" class="direction-btn up-btn" icon="tui:arrow-up"></tui-button>
        <div class="horizontal-buttons">
          <tui-button v-if="visibleButtons.includes('left')" circle @click="handleDirectionChange('left')" class="direction-btn left-btn" icon="tui:arrow-left"></tui-button>
          <tui-button v-if="visibleButtons.includes('right')" circle @click="handleDirectionChange('right')" class="direction-btn right-btn" icon="tui:arrow-right"></tui-button>
        </div>
        <tui-button v-if="visibleButtons.includes('down')" circle @click="handleDirectionChange('down')" class="direction-btn down-btn" icon="tui:arrow-down"></tui-button>
      </div>

      <!-- 功能键（右侧，垂直排列） -->
      <div class="function-controls" v-if="visibleButtons.includes('function1') || visibleButtons.includes('function2')">
        <tui-button v-if="visibleButtons.includes('function1')" circle @click="handleFunctionButtonClick('function1')" class="function-btn function1-btn" icon="tui:attack"></tui-button>
        <tui-button v-if="visibleButtons.includes('function2')" circle @click="handleFunctionButtonClick('function2')" class="function-btn function2-btn" icon="tui:arrow-up"></tui-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue';
import type { TuiControlPanelProps, TuiControlPanelEmits } from './types';

// 定义props
const props = defineProps<TuiControlPanelProps>();

// 定义emit事件
const emit = defineEmits<TuiControlPanelEmits>();

// 组件内部状态
const controlPanelRef = ref<HTMLDivElement | null>(null);
const isFixed = ref(props.isFixed ?? true);
// 默认显示四个方向键和两个功能键
const visibleButtons = ref(props.visibleButtons ?? ['up', 'down', 'left', 'right', 'function1', 'function2']);

// 监听props变化
watch(() => props.isFixed, (newValue) => {
  isFixed.value = newValue ?? true;
  updatePositionMode();
});

watch(() => props.visibleButtons, (newValue) => {
  visibleButtons.value = newValue ?? ['up', 'down', 'left', 'right', 'function1', 'function2'];
});

// 处理方向改变
const handleDirectionChange = (direction: string) => {
  emit('directionChange', direction);
};

// 处理功能键点击
const handleFunctionButtonClick = (functionType: string) => {
  emit('functionButtonClick', functionType);
};

// 拖拽相关变量和函数
let isDragging = false;
let offsetX = 0;
let offsetY = 0;

const handleMouseDown = (e: MouseEvent) => {
  if (isFixed.value) return;
  isDragging = true;
  const rect = controlPanelRef.value!.getBoundingClientRect();
  offsetX = e.clientX - rect.left;
  offsetY = e.clientY - rect.top;
};

const handleMouseMove = (e: MouseEvent) => {
  if (!isDragging || !controlPanelRef.value) return;

  // 计算新位置
  let newX = e.clientX - offsetX;
  let newY = e.clientY - offsetY;

  // 限制在视口范围内
  const padRect = controlPanelRef.value.getBoundingClientRect();
  newX = Math.max(0, Math.min(newX, window.innerWidth - padRect.width));
  newY = Math.max(0, Math.min(newY, window.innerHeight - padRect.height));

  updatePosition(newX, newY);
};

const handleMouseUp = () => {
  isDragging = false;
};

// 触摸事件支持
const handleTouchStart = (e: TouchEvent) => {
  if (isFixed.value) return;
  isDragging = true;
  const rect = controlPanelRef.value!.getBoundingClientRect();
  const touch = e.touches[0];
  offsetX = touch.clientX - rect.left;
  offsetY = touch.clientY - rect.top;
};

const handleTouchMove = (e: TouchEvent) => {
  if (!isDragging || !controlPanelRef.value) return;

  const touch = e.touches[0];
  // 计算新位置
  let newX = touch.clientX - offsetX;
  let newY = touch.clientY - offsetY;

  // 限制在视口范围内
  const padRect = controlPanelRef.value.getBoundingClientRect();
  newX = Math.max(0, Math.min(newX, window.innerWidth - padRect.width));
  newY = Math.max(0, Math.min(newY, window.innerHeight - padRect.height));

  updatePosition(newX, newY);

  e.preventDefault(); // 防止页面滚动
};

const handleTouchEnd = () => {
  isDragging = false;
};

// 更新位置
const updatePosition = (x: number, y: number) => {
  if (!controlPanelRef.value) return;

  controlPanelRef.value.style.right = 'auto';
  controlPanelRef.value.style.bottom = 'auto';
  controlPanelRef.value.style.left = `${x}px`;
  controlPanelRef.value.style.top = `${y}px`;
};

// 更新位置模式
const updatePositionMode = () => {
  if (isFixed.value) {
    // 移除resetToFixedPosition()调用，使控制面板在固定时保持当前位置
    cleanupDraggable();
  } else {
    setupDraggable();
  }
};

// 设置拖拽功能
const setupDraggable = () => {
  if (!controlPanelRef.value) return;

  // 添加事件监听器
  controlPanelRef.value.addEventListener('mousedown', handleMouseDown);
  document.addEventListener('mousemove', handleMouseMove);
  document.addEventListener('mouseup', handleMouseUp);
  controlPanelRef.value.addEventListener('touchstart', handleTouchStart);
  document.addEventListener('touchmove', handleTouchMove as EventListener);
  document.addEventListener('touchend', handleTouchEnd);
};

// 清理拖拽事件
const cleanupDraggable = () => {
  if (!controlPanelRef.value) return;

  // 移除事件监听器
  controlPanelRef.value.removeEventListener('mousedown', handleMouseDown);
  document.removeEventListener('mousemove', handleMouseMove);
  document.removeEventListener('mouseup', handleMouseUp);
  controlPanelRef.value.removeEventListener('touchstart', handleTouchStart);
  document.removeEventListener('touchmove', handleTouchMove as EventListener);
  document.removeEventListener('touchend', handleTouchEnd);

  // 重置拖拽状态
  isDragging = false;
};

// 初始化组件
onMounted(() => {
  // 应用初始位置
  if (controlPanelRef.value && props.initialPosition) {
    const { top, left, bottom, right } = props.initialPosition;

    if (top !== undefined) controlPanelRef.value.style.top = top;
    if (left !== undefined) controlPanelRef.value.style.left = left;
    if (bottom !== undefined) controlPanelRef.value.style.bottom = bottom;
    if (right !== undefined) controlPanelRef.value.style.right = right;
  }

  // 设置初始位置模式
  updatePositionMode();
});

// 清理组件
onUnmounted(() => {
  cleanupDraggable();
});
</script>

<style lang="scss" scoped>
.floating-control-panel {
  position: fixed;
  right: 10px;
  bottom: 10px;
  z-index: 1000;
  background-color: transparent;
  border-radius: 10px;
  padding: 10px;
  box-shadow: none;

  &.draggable {
    cursor: move;
    user-select: none;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  }

  &.fixed {
    cursor: default;
    transition: all 0.3s ease;
  }

  .control-panel {
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: clamp(15px, 8vw, 40px);

    // 功能键垂直排列（右侧）
    .function-controls {
      display: flex;
      flex-direction: column;
      gap: clamp(15px, 8vw, 40px);
    }

    // 功能键样式
    .function-btn {
      width: clamp(30px, 10vw, 45px);
      height: clamp(30px, 10vw, 45px);
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
      font-size: clamp(14px, 4vw, 18px);
      box-sizing: border-box;
      opacity: 0.3;
      transition: opacity 0.2s;
      background-color: rgba(255, 255, 255, 0.1);

      &:hover,
      &:active {
        opacity: 0.5;
      }

      &.function1-btn {
        background-color: rgba(0, 255, 0, 0.1);
      }

      &.function2-btn {
        background-color: rgba(0, 191, 255, 0.1);
      }
    }

    .direction-controls {
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .direction-btn {
      width: clamp(35px, 12vw, 50px);
      height: clamp(35px, 12vw, 50px);
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
      font-size: clamp(14px, 4vw, 18px);
      margin: 3px 0;
      box-sizing: border-box;
      opacity: 0.3;
      transition: opacity 0.2s;

      &:hover,
      &:active {
        opacity: 0.5;
      }
    }

    .horizontal-buttons {
      display: flex;
      justify-content: center;
      gap: clamp(15px, 8vw, 40px);
      margin: 0;
      width: 100%;

      .left-btn,
      .right-btn {
        margin: 0 3px;
      }
    }
  }
}
</style>